package com.example.secondhandspringboot.controller;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.secondhandspringboot.constant.MessageConstant;
import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.entity.File;
import com.example.secondhandspringboot.exception.FileUploadException;
import com.example.secondhandspringboot.results.Result;
import com.example.secondhandspringboot.service.IFileService;
import com.example.secondhandspringboot.utils.AliOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;

@RequestMapping("/file")
@CrossOrigin
@RestController
@RequiredArgsConstructor
@Slf4j
public class FileUploadController {

    private final IFileService fileService;


    /**
     * 头像图片等文件上传
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile multipartFile) throws Exception {
        log.info("文件上传，文件名：{}",multipartFile.getOriginalFilename());
        String originalFilename = multipartFile.getOriginalFilename();
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = AliOssUtil.uploadFile(filename,multipartFile.getInputStream());
        return Result.success(url);
    }

    /**
     * 校林网盘上传文件
     * @return
     * @throws Exception
     */
    @PostMapping("/netDiskUpload")
    public Result netDiskUpload(MultipartFile multipartFile,@RequestParam(required = false) Long folderId) throws Exception{
        if (multipartFile == null || multipartFile.isEmpty()){
            throw new FileUploadException(MessageConstant.FILE_UPLOAD_ERR);
        }
        // 判断文件大小不超过100MB
        if (multipartFile.getSize() / 1048576 > 100){
            throw new FileUploadException(MessageConstant.FILE_SIZE_REE);
        }
        Long currentId = BaseContext.getCurrentId();
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件信息
        File file = new File();
        file.setFileName(originalFilename);
        file.setContentType(multipartFile.getContentType());
        file.setDowmloadCount(0L);
        file.setFlieSize(multipartFile.getSize());
        file.setUserId(currentId);
        //如果folderId为null则在最顶级目录中
//        folderId.ifPresentOrElse(file::setFolderId,()->file.setFolderId(null));
        file.setFolderId(folderId);
        file.setUploadDate(LocalDateTime.now());

//        String filename = UUID.randomUUID().toString()+ originalFilename.substring(originalFilename.lastIndexOf('.'));
        String filename = originalFilename.substring(0,originalFilename.lastIndexOf('.'))+LocalDateTime.now().toString().replaceAll("[-:.T]+","").substring(0,15)+ originalFilename.substring(originalFilename.lastIndexOf('.'));
        //将文件上传到阿里云oss并返回文件地址
        String url = AliOssUtil.uploadFile(filename,multipartFile.getInputStream());

        file.setFilePath(url);
        Db.save(file);
        return Result.success();
    }


    /**
     * 校林网盘下载文件
     * @return
     * @throws Exception
     */
    @GetMapping("/netDiskDownload/{fileId}")
    public Result<String> netDiskDownload(@PathVariable Long fileId){
        File fileOne = fileService.getById(fileId);
        if (fileOne == null){
            throw new FileUploadException(MessageConstant.FILE_DOWNLOAD_REE);
        }
        return Result.success(fileOne.getFilePath());
    }
}
